<template>
    <view class="page">
        <u-navbar title="登录" :back-icon-color="'#ffffff'" :title-color="'#ffffff'" :background="background"></u-navbar>
        <view class="f__login">
            <view class="logo">
                <image class="img" :src="$imgUrl+'logo01.png'" mode="heightFix"></image>
            </view>
            <view class="title">欢迎登录~</view>
            <view class="text">用户登录后消费可享受折扣，享受更好的服务体验</view>
            <view class="loginButton" v-if="!isPhoneLogin">
                <!-- #ifdef MP-WEIXIN -->
                <!-- <button v-if="isAuthor" class="button" :class="{'gray':!isChecked}" :disabled="!isChecked" @click="onAuthorization" :style="{background:PrimaryColor}">微信授权登录</button> -->
                <!-- v-if="!isAuthor" -->
                <u-button throttle-time="1000" type="success" :disabled="isChecked==false" open-type="getPhoneNumber"
                    @getphonenumber="decryptPhoneNumber">手机号快捷登录</u-button>
                <!-- 此功能需微信认证 -->
                <!-- #endif -->
                <u-button :custom-style="customStyle" @click="toHome()">暂不登录</u-button>
            </view>
            <view class="content-label">
                <view class="radio">
                    <view class="pic" @click="isChecked = !isChecked">
                        <image :src="$imgUrl+'login/select.png'" mode="" v-if="isChecked"></image>
                        <image :src="$imgUrl+'login/no.png'" mode="" v-else></image>
                    </view>
                    我已阅读并同意<text style="color:#0080f6" @click="policy(1)">《隐私政策》</text>和<text style="color: #0080f6"
                        @click="policy(2)">《服务协议》</text>
                </view>
            </view>
        </view>
        <public-module></public-module>
    </view>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import {
    getMobileToMiniLogin, authMiniLogin
} from "@/api/login.js"
var clear;
export default {
    name: 'f-login',
    computed: {
        ...mapState({
            loginPopupShow: state => state.user.loginPopupShow,
        }),
        show: {
            get() { return this.loginPopupShow },
            set(val) { }
        }
    },
    data() {
        return {
            // #ifndef MP-ALIPAY
            PrimaryColor: '#1fba1a', //主题色
            // #endif
            readonly: false,
            phone: '', //号码
            code: '',  //uni.login获取的code
            $imgUrl: this.$imgUrl,
            isChecked: false,
            showToast: false,
            isAuthor: false,
            background: {
                // 渐变色
                backgroundImage: 'linear-gradient(to bottom right, #2e996f, #3f99ab)'
            },
            customStyle: {
                marginTop: '15px',
            }
        };
    },
    onShow() {
        this.getLoginByUnion()
        if (uni.getStorageSync('mobile')) {
            this.isAuthor = true
        }
    },
    methods: {
        onBack() {
            uni.navigateBack();
        },
        // 协议
        policy(e) {
            // #ifdef H5
            this.$navigateTo({
                url: "/pagesA/login/agreenment",
                params: {
                    type: e,
                },
            });
            // #endif
            // #ifndef H5
            let link = "https://h5.weilankangyang.com/#/pagesA/login/agreenment?type=" + e
            uni.navigateTo({
                url: '/pagesA/login/tool?link=' + encodeURIComponent(link)
            })
            // #endif
        },
        ...mapMutations(['setLoginPopupShow', 'setUserInfo', "SET_TEL"]),
        //个人信息授权登录
        onAuthorization(e) {
            // #ifdef MP-WEIXIN
            this.$store.commit('setShowWxLogin', true) //打开微信新授权组件
            this.getUserInfo(info => {
                console.log(info, '授权信息')
                let httpData = {
                    code: this.code,
                    nickName: info.nickName || '', //昵称
                    avatarUrl: info.avatarUrl || '', //头像
                    gender: info.gender || '', //性别 0:未知 1:男 2:女
                }
                // uni.$u.http.post('您的接口', httpData).then(res => {
                let userInfo = {
                    // ...res,
                    token: true,//token用于判断是否登录
                }
                // this.setUserInfo(userInfo)
                // setTimeout(()=>{
                //     uni.showToast({
                //     	title: '登录成功',
                //     	icon: 'none'
                //     });
                //     this.closeLogin();
                // },100)
                // })
            }, err => {
                // this.closeLogin();
            })
            // #endif
        },
        //授权手机号登录
        decryptPhoneNumber(e) {
            console.log(e, '授权手机号')
            var that = this
            // #ifdef MP-WEIXIN
            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                if (e.detail.iv) {
                    var userInfo = e.detail;
                    userInfo.code = that.code
                    // this.closeLogin();
                    //请去getPhoneInfo方法中使用您的接口绑定信息
                    this.getPhoneInfo(userInfo, res => {
                        this.isAuthor = true
                    });
                } else {
                    // 授权失败请使用验证码登录
                    this.isPhoneLogin = true
                    uni.showToast({
                        title: '授权失败',
                        icon: 'none'
                    });
                }
            } else {
                // this.closeLogin()
            }
            // #endif
        },
        getPhoneInfo(info, successCallback, errCallback) {
            console.log(info, "info")
            let httpData = {}
            httpData = {
                code: info.code, //小程序code
                iv: info.iv, //小程序加密算法的初始向量
                encryptedData: info.encryptedData, //包括敏感数据在内的完整用户信息的加密数据
            };
            getMobileToMiniLogin(httpData).then(res => {
                if (res.code == 1) {
                    console.log(res, "获取手机号")
                    this.SET_TEL(res.data.mobile)
                    uni.setStorageSync('mobile', res.data.mobile)
                    this.phoneLogin(res.data.mobile)
                    successCallback && successCallback(res)
                }

            }, err => {
                errCallback && errCallback(err)
            });
        },
        phoneLogin(mobile) {
            uni.login({
                success: (res) => {
                    console.log(res, 'dengluinfo')
                    let httpData = {
                        code: res.code,
                        mobile: mobile,
                        avatar: '',
                        nicename: '',
                        invite_code: uni.getStorageSync("invite") ? uni.getStorageSync("invite") : '',
                    };
                    authMiniLogin(httpData).then(ress => {
                        if (ress.code == 1) {
                            console.log(ress.data, '登录数据')
                            uni.setStorageSync('token', ress.data.token)
                            // uni.setStorageSync('isLogin', true)
                            uni.setStorageSync('invite_code', ress.data.invite_code)
                            uni.setStorageSync('huanxin', JSON.stringify(ress.data.huanxin))
                            uni.showToast({
                                title: ress.info,
                                icon: 'none'
                            });
                            // this.$store.commit('setShowWxLogin', true)
                            if (ress.data.busin_id) {
                                uni.setStorageSync('busin_id', ress.data.busin_id)
                                setTimeout(() => {
                                    let pages = getCurrentPages();
                                    let currentPage = getCurrentPages().pop();
                                    var prePage = pages[pages.length - 2]
                                    console.log(pages.length, '分享打印')
                                    if (pages.length > 1) {
                                        uni.navigateBack({
                                            delta: 1
                                        })
                                        // prePage.$vm.getList()
                                        // prePage.onLoad()
                                        // prePage.onShow()
                                        currentPage.onLoad()
                                        currentPage.onShow()
                                    } else {
                                        uni.reLaunch({
                                            url: '/pages/my/my'
                                        })
                                    }
                                }, 500)
                            }
                            // else {
                            //     setTimeout(() => {
                            //         uni.navigateTo({
                            //             url: '/pagesA/login/register'
                            //         })
                            //     }, 500)
                            // }
                        }
                    })
                }
            })
        },
        closeLogin() {
            this.setLoginPopupShow(false);
        },
        // 自动静默登录----获取code
        // 静默登录：就是已经登录过的用户，被迫下线。调用此接口快速登录
        getLoginByUnion() {
            var that = this
            uni.login({
                success(res) {
                    console.log(res, "获取code")
                    that.code = res.code
                    let httpData = {
                        code: res.code,
                    }
                    // uni.$u.http.post('您的接口', httpData).then(res => {
                    setTimeout(() => {
                        // 自动静默登录失败--打开手动登录
                        that.isLoading = false
                    }, 500)
                    // }).catch(()=>{
                    //     // 自动静默登录失败--打开手动登录
                    //     that.isLoading = false
                    // })
                }
            })
        },
        getUserInfo(successCallback, errorCallback) {
            uni.showLoading({
                title: '正在申请授权',
            });
            // #ifdef MP-WEIXIN
            uni.getUserProfile({
                desc: '用于完善会员资料',
                success: function (res) {
                    uni.hideLoading()
                    var offUserInfo = res.userInfo
                    successCallback && successCallback(offUserInfo)
                },
                fail: (res) => {
                    uni.hideLoading()
                    errorCallback && errorCallback(res)
                }
            })
            // #endif
        },
        toHome() {
            uni.reLaunch({
                url: '/pages/index/index'
            })
        }
    }
};
</script>

<style lang="scss" scoped>
.page {
    width: 100vw;
    height: 100vh;
    background-color: #fff;

    .f__login {
        padding: 120rpx 32rpx 48rpx;
        border-radius: 18rpx 18rpx 0 0;
        z-index: 99;

        .logo {
            // width: 90rpx;
            height: 90rpx;
            border-radius: 18rpx;
            overflow: hidden;
            //   display: flex;
            justify-content: center;

            .img {
                width: 90rpx;
                height: 90rpx;
            }
        }

        .title {
            font-size: 40rpx;
            font-weight: bold;
            margin-top: 24rpx;
        }

        .text {
            font-size: 24rpx;
            color: #666;
            margin-top: 16rpx;
        }

        .loginButton {
            margin-top: 56rpx;

            .button {
                color: #fff;
                width: 100%;
                height: 92rpx;
                opacity: 1;
            }

            .gray {
                opacity: 0.3;
            }

            .marginT {
                margin-top: 24rpx;
            }
        }
    }

    .content-label {
        font-size: 24rpx;
        color: #999999;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 30rpx 0;

        .radio {
            display: flex;
            align-items: center;

            .pic {
                padding: 20rpx;

                image {
                    width: 30rpx;
                    height: 30rpx;
                    //   margin-right: 18rpx;
                }
            }
        }
    }
}
</style>
